const Router = require('koa-router');
const common = require('../libs/common');
const db = require('../libs/db');
const _ = require('underscore');
let router = new Router();
const response = require('../libs/result');
const lang = require('../lang/language');
const random = require('string-random')
const koa2Req = require('koa2-request')


/**
 * @api {post} /api/v1/product/getextendprolist  没有匹配到贷款产品推荐其他平台列表
 * @apiDescription 没有匹配到贷款产品推荐其他平台列表
 * @apiName getextendprolist
 * @apiSampleRequest /api/v1/product/getextendprolist
 * @apiGroup product
 * @apiVersion 2.0.0
 */
router.post('/getextendprolist', async ctx => {
    let products=await ctx.db.query(`select c.id,c.name,c.package_name,c.download_uri,c.is_googleplay_package,c.loan_currency,c.loan_type,c.loan_rate,c.product_type
    ,c.product_jump_type,c.product_uri,c.images,c.promotion_icon,c.feature,c.button_content,c.product_image from  products_product c where c.api_type=0 and c.product_status=0`,[]);
    products.map(function(item, index, input){
        item.images = ctx.config.productimgurl + item.images;
        item.product_image = ctx.config.productimgurl + item.product_image;
        item.promotion_icon = ctx.config.productimgurl + item.promotion_icon;
    })

    ctx.body = common.handleResulte(200, products, '')
})


/**
 * @api {post} /api/v1/product/loanagreement  借款协议
 * @apiDescription 借款协议
 * @apiName loanagreement
 * @apiParam (参数) {Number} productid   产品id
 * @apiParam (参数) {Number} userid   用户id
 * @apiParam (参数) {Number} useramount   贷款额度
 * @apiParam (参数) {Number} userperiod   贷款期限
 * @apiSampleRequest /api/v1/product/loanagreement
 * @apiGroup product
 * @apiVersion 2.0.0
 */
router.post('/loanagreement', async ctx => {
  try {
    let { productid,userid,useramount,userperiod } = ctx.request.body;

    //产品信息
    let product=await ctx.db.query(`select * from  products_product where id=?`,[parseInt(productid)]);
    
    product=product[0];
    //根据手机号获取借款人信息
    let loan_user = await ctx.db.query(`select b.* from auth_user a,loan_user b where a.phone_number=b.mobile and a.id=?`, [parseInt(userid)]);
loan_user=loan_user[0];
    let jsondata = {
      appId: product.appid,
      productId: product.partner_id,
      credentialNo:loan_user.id_card_number,
      mobile:loan_user.mobile,
      userName:loan_user.name,
      amount:parseInt(useramount),
      period:parseInt(userperiod)
    };
    let signstr = common.signjsapi(jsondata, product.key)
  
    //jsondata.sign = signstr;
    var options = {
      method: 'post',
      url: product.domain+"/loan/contract_link",
      json: signstr,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    }
    let reslink = await koa2Req(options);
    console.log(reslink);
    reslink = JSON.parse(reslink)
   if(reslink.data.body.code==0){
    response(ctx, 200, reslink.data)
   }else{
    response(ctx, 200, '', "没有获取到借款协议")
   }
    
  } catch (error) {
    console.log(error);
    response(ctx, 201, '', "没有获取到借款协议")
  }
})

/**
 * @api {post} /api/v1/product/loanstep  借款步骤
 * @apiDescription 借款步骤
 * @apiName loanstep
 * @apiParam (参数) {Number} productid   产品id
 * @apiSampleRequest /api/v1/product/loanstep
 * @apiGroup product
 * @apiVersion 2.0.0
 */
router.post('/loanstep', async ctx => {
    let { productid } = ctx.request.body;
    let step = await ctx.db.query(`SELECT title,images,description FROM product_product_loan_step WHERE product_id_id=? AND step_type=? AND country_id=?`, [productid, 0, 1]);
    step.map(function (rds, index, input) {
        rds.images = ctx.config.productimgurl + rds.images;
    });
    response(ctx, 200, step, "steplist")
})

/**
 * @api {post} /api/v1/product/querylist  产品列表(含广告)
 * @apiDescription 产品列表(含广告)
 * @apiName querylist
 * @apiParam (参数) {String} channel   渠道包名
 * @apiParam (参数) {String} page   页数，从1开始
 * @apiParam (参数) {String} pageSize   每页条数, 默认6条
 * @apiSampleRequest /api/v1/product/querylist
 * @apiGroup product
 * @apiVersion 2.0.0
 */
router.post('/querylist', async ctx => {
    let { channel, page, pageSize } = ctx.request.body;
    //console.log(channel);
    channel='com.skeytks.uhnetc';
    //channel='com.vn.gethoa.cho';
    let sqltotal = `SELECT COUNT(1) AS count FROM moduleconfig_channelpackage a  ,moduelconfig_product b ,products_product c
    WHERE a.channel='${channel}' AND a.module_id= b.module_id AND b.product_id=c.id and c.is_active = 1 and c.product_status = 0  and b.is_active = 1 AND c.product_jump_type<>9`;
    console.log('1开始时间'+new Date())
    let total = (await db.querysql(ctx, sqltotal))[0].count;
    console.log(total);
    console.log('1结束时间'+new Date())
    // let selectStr = `SELECT c.id,c.name,c.package_name,c.is_googleplay_package,c.loan_currency,c.loan_type,c.loan_rate,c.product_type
    // ,c.product_jump_type,c.product_uri,c.images,c.promotion_icon,c.feature,c.button_content,c.product_image
    //  AS count FROM moduleconfig_channelpackage a  ,moduelconfig_product b ,products_product c
    // WHERE a.channel='${channel}' AND a.module_id= b.module_id AND b.product_id=c.id order by b.order desc
    // LIMIT ${(page - 1) * pageSize}, ${pageSize}`;

    let selectStr=`SELECT * FROM (
        SELECT t.*,ifNULL(k.pullcount,0) AS pullcount  FROM (SELECT c.id,c.name,c.package_name,c.is_googleplay_package,c.loan_currency,c.loan_type,c.loan_rate,c.product_type
            ,c.product_jump_type,c.product_uri,c.images,c.promotion_icon,c.feature,c.button_content,c.product_image,c.limit_num,b.order
               FROM moduleconfig_channelpackage a  ,moduelconfig_product b ,products_product c
            WHERE a.channel='${channel}' AND a.module_id= b.module_id AND b.product_id=c.id and c.is_active = 1 and c.product_status = 0  and b.is_active = 1 AND c.product_jump_type<>9    order by b.order DESC) t LEFT join
            (SELECT COUNT(product_id) AS pullcount,product_id FROM loan_order WHERE pull_status=1 AND DATE_FORMAT(push_date,'%m-%d-%Y')=DATE_FORMAT(NOW(),'%m-%d-%Y') GROUP BY product_id)
         k ON t.id=k.product_id   order by t.order DESC
         )  m WHERE   pullcount<m.limit_num or m.limit_num=0
            
         LIMIT ${(page - 1) * pageSize}, ${pageSize}`
    console.log('2开始时间'+new Date())
    let data = await db.querysql(ctx, selectStr);
    console.log(data);
    console.log('2结束时间'+new Date())
    let sqlmin = 'SELECT min(b.amount) as  amount from products_product_loan_amount a,products_loanamount b WHERE a.loanamount_id = b.id AND a.product_id=';
    let sqlmax = 'SELECT max(b.amount) as  amount from products_product_loan_amount a,products_loanamount b WHERE a.loanamount_id = b.id AND a.product_id=';
    let strsql = `SELECT c.images,c.link,c.link_type FROM moduleconfig_channelpackage a,moduelconfig_banner b,featured_featured c
    WHERE a.channel='${channel}' AND a.module_id= b.module_id AND c.id= b.banner_id AND c.type=0 order by b.order desc LIMIT ${(page - 1) * pageSize}, ${pageSize}`;
    console.log('3开始时间'+new Date())
    let featureddata = await db.querysql(ctx, strsql);
    console.log(featureddata);
    console.log('3结束时间'+new Date())
    let newrows = [];
    let i = 0;
    for (let index = 0; index < data.length; index++) {
        let item = data[index];
        item.images = ctx.config.productimgurl + item.images;
        item.product_image = ctx.config.productimgurl + item.product_image;
        item.promotion_icon = ctx.config.productimgurl + item.promotion_icon;
        let mindata = await db.querysql(ctx, sqlmin + item.id);
        let maxdata = await db.querysql(ctx, sqlmax + item.id);
        let min = 0;
        let max = 0;
        if (mindata.length > 0) {
            min = mindata[0].amount ? mindata[0].amount : 0;
        }
        if (maxdata.length > 0) {
            max = maxdata[0].amount ? maxdata[0].amount : 0;
        }
        item.amount_range = min + '~' + max;
        item.isproduct = true;
        newrows.push(item);
        if ((index + 1) % 3 == 0) {
            // 跳转类型   1   tag 产品列表    2   内部H5     3   外部H5    4   apk下载     5    跳转首页      7    指定产品页
            let obj;
            if (featureddata.length > i) {
                obj = featureddata[i];
                i++;
                obj.product_jump_type=obj.link_type;
                obj.product_uri=obj.link
                obj.isproduct = false;
                obj.images = ctx.config.productimgurl + obj.images;
                switch (obj.link_type) {
                    case 1:
                        obj.link_type_msg = 'tag 产品列表';
                        break;
                    case 2:
                        obj.link_type_msg = '内部H5';
                        break;
                    case 3:
                        obj.link_type_msg = '外部H5';
                        break;
                    case 4:
                        obj.link_type_msg = 'apk下载';
                        break;
                    case 5:
                        obj.link_type_msg = '跳转首页';
                        break;
                    case 7:
                        obj.link_type_msg = '指定产品页';
                        break;
                    default:
                        obj.link_type_msg = '未知6';
                        break;
                }
                newrows.push(obj);
            }
        }
    }
    let res = {
        rows: newrows,
        total: total,
        curPage: +page,
        pageSize: +pageSize
    };

    response(ctx, 200, res, '产品列表');
})

/**
* @api {post} /api/v1/product/queryById  产品详情
* @apiDescription 产品详情
* @apiName queryById
* @apiParam (参数) {String} id 产品编号id
* @apiSampleRequest /api/v1/product/queryById
* @apiGroup product
* @apiVersion 1.0.0
*/
router.post('/queryById', async ctx => {
    let { id } = ctx.request.body;
    //借款额度
    let sql = `SELECT b.amount as  amount from products_product_loan_amount a,products_loanamount b WHERE a.loanamount_id = b.id AND a.product_id=${id} order by b.amount  limit 1`;
    let amountitems = await db.querysql(ctx, sql);
    //借款期限
    let sql2 = `SELECT a.period FROM products_loanperiod a, products_product_period b WHERE  a.id=b.loanperiod_id AND b.product_id=${id} order by a.period limit 1`;
    let proiditems = await db.querysql(ctx, sql2);
    //该产品总订单数量
    let totalsql = `SELECT count(1) as total FROM loan_order WHERE order_status>=170 AND product_id=${id}`;
    let count = (await db.querysql(ctx, totalsql))[0].total;
    
    //产品详情
    let products_product = await db.queryById(ctx, 'products_product', id);
   
    let a = {
        'loan_amount': amountitems[0].amount,//默认借款额度
        'period': proiditems[0].period //默认借款期限
    };
    //管理费
    if (products_product) {
        
        /** 管理费计算方式    (0, '本金*天数*管理利率'), (1, '本金*管理利率'), (2, '固定金额') */
        let admin_mount = 0;
        switch (products_product.admin_amount_type) {
            case 0:
                admin_mount = common.mul(common.mul(a.loan_amount, products_product.admin_amount), a.period);
                break;
            case 1:
                admin_mount = common.mul(a.loan_amount, products_product.admin_amount);
                break;
            case 2:
                admin_mount = products_product.admin_amount;
                break;
            default:
                break;
        }
        /** 计算利息 loan_rate利率*/
        let lmount = common.mul(common.mul(a.loan_amount, products_product.rate), a.period);

        /** 贷款模式      (0, _('预扣利息模式')), (1, _('非预扣利息模式')) */
        switch (products_product.loan_type) {
            // 计算实际到账金额和总还款额
            case 0:
                // 实际到账金额 = 额度-利息-管理费
                a.actual_amount = common.sub(common.sub(a.loan_amount, lmount), admin_mount);
                // 总还款额=本金
                a.repay_total_amount = a.loan_amount;
                break;
            case 1:
                // 实际到账金额 = 额度-管理费
                a.actual_amount = common.sub(a.loan_amount, admin_mount);
                // 总还款额=本金+利息
                a.repay_total_amount = common.add(a.loan_amount, lmount);
                break;
            default:
                break;
        }

        // 利息+管理费
        a.admin_amount = common.add(lmount, admin_mount);
        a.id = id;
        a.name = products_product.name;
        if (products_product) {
            a.images = ctx.config.productimgurl + products_product.images;
        }

        a.product_jump_type=products_product.product_jump_type;
        a.download_type=products_product.download_type;
        a.download_uri=products_product.download_uri;
        a.amountitems = amountitems;
        a.proiditems = proiditems;
        a.successnum = count;
        //是否有扩展合同页
        a.api_amount=products_product.api_amount;
        //是否有合同页
        a.api_contract=products_product.api_contract;
        a.loan_amount_msg = lang(ctx,'贷款额度');
        a.period_msg = lang(ctx,'贷款期限');
        a.actual_amount_msg = lang(ctx,'实际到账金额');
        a.repay_total_amount_msg = lang(ctx,'总还款额');
        a.admin_amount_msg = lang(ctx,'利息+管理费');
        a.amountitems_msg = lang(ctx,'额度数组');
        a.proiditems_msg = lang(ctx,'期限数组');
        a.successnum_msg = lang(ctx,'成功借款人数');
    }else{
        response(ctx, 201, '', '未取到额度和期限配置信息');
        return;
    }

    response(ctx, 200, a, '产品详情');
})

/**
 * @api {post} /api/v1/product/queryComment  产品评论
 * @apiDescription 产品评论
 * @apiName queryComment
 * @apiParam (参数) {String} pid 产品编号id
 * @apiParam (参数) {String} page   页数，从1开始
 * @apiParam (参数) {String} pageSize   每页条数
 * @apiSampleRequest /api/v1/product/queryComment
 * @apiGroup product
 * @apiVersion 1.0.0
 */
router.post('/queryComment', async ctx => {
    let { pid, page, pageSize } = ctx.request.body;
    if (pid) {
        let data = await ctx.db.query('select * from content_googleplay_comment where product_id=? order by comment_time desc limit ?,?', [pid, (page - 1) * pageSize, pageSize]);
        response(ctx, 200, data, '产品评论');
    } else {
        response(ctx, 201, '', '产品编号不能为空');
    }
})



module.exports = router.routes()